/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * inicioSesion.java
 *
 * Created on 16/11/2010, 11:20:45 PM
 */
package zonasoft.Vistas;

import java.io.IOException;
import zonasoft.Conceptos.Usuario;
import zonasoft.Manejadores.ManejadorUsuario;
import net.java.swingfx.waitwithstyle.InfiniteProgressPanel;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.jvnet.substance.SubstanceLookAndFeel;
import zonasoft.Utilidades.ConfiguracionInicial;
import zonasoft.Utilidades.HTTPRequestPoster;
import zonasoft.Utilidades.mailMac;
import zonasoft.Vistas.Negocio.RegistrarZonificado;

/**
 *
 * @author JORGE
 */
public class inicioSesion extends javax.swing.JFrame {

    public static Usuario userActual;
    public static Timestamp fechaInicioSesion;
    //public static ConfiguracionInicial config=new ConfiguracionInicial("configuracion.properties");
    public static ConfiguracionInicial config = new ConfiguracionInicial("configuracion.properties");

    /** Creates new form inicioSesion */
    public inicioSesion() throws SQLException {
        super("::ZonaSoft 1.0:: Inicio de Sesion");
        initComponents();
        setLocationRelativeTo(null);
        try {
            configuracionInicial();
        } catch (IOException ex) {
            Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtLogin = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        jButtonInicioSesion = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle(" ZonaSoft-1.0 ");
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.lightGray, java.awt.Color.gray));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBackground(java.awt.Color.white);
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Lucida Bright", 1, 14));
        jLabel1.setText("Usuario");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 14, 69, -1));

        txtLogin.setFont(new java.awt.Font("Lucida Bright", 2, 14));
        jPanel1.add(txtLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 11, 209, -1));

        jLabel2.setFont(new java.awt.Font("Lucida Bright", 1, 14));
        jLabel2.setText("Contraseña");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, -1));

        txtPassword.setFont(new java.awt.Font("Lucida Bright", 2, 14));
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });
        jPanel1.add(txtPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 40, 209, -1));

        jButtonInicioSesion.setFont(new java.awt.Font("Lucida Bright", 1, 12));
        jButtonInicioSesion.setText("Iniciar");
        jButtonInicioSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInicioSesionActionPerformed(evt);
            }
        });
        jPanel1.add(jButtonInicioSesion, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 70, -1, -1));

        jButton2.setFont(new java.awt.Font("Lucida Bright", 1, 12));
        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 70, -1, -1));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zonasoft/Vistas/iconos/AbannerOrigin.png"))); // NOI18N
        jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(326, 11, 70, 83));

        jPanel2.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(-2, 59, 400, 100));

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zonasoft/Vistas/iconos/AbannerOriginal.png"))); // NOI18N
        jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, -1));

        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 160));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonInicioSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInicioSesionActionPerformed
        // TODO add your handling code here:
        inicioDeSesion();

    }//GEN-LAST:event_jButtonInicioSesionActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        //metodo deprecado para cerrar la venta
        //        this.hide();
        int resp = JOptionPane.showConfirmDialog(this, "Realmente deseas salir ", "Warning", JOptionPane.YES_NO_OPTION);
        if (resp == JOptionPane.YES_OPTION) {
            // JOptionPane.showMessageDialog(this,"Gracias por usar ZonaSoft");
            this.dispose();

        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        // TODO add your handling code here:
        if ((evt.getKeyCode() == KeyEvent.VK_ENTER)) {
            inicioDeSesion();
        }


    }//GEN-LAST:event_txtPasswordKeyPressed

    public void configuracionInicial() throws IOException {
        config.cargarArchivo();
//        config.cargarArchivo2();
        String skin = config.buscarPropiedad("ventana.skin");
        SubstanceLookAndFeel.setSkin(skin);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//         try{
//      //  UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");
//              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//        }catch (Exception e){
//       e.printStackTrace();
//       }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new inicioSesion().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    /* public static void main(String args[]) {
    
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    //new inicioSesion().setVisible(true);
    
    }
    });
    }*/
    int numeroInicio = 0;

    private void inicioDeSesion() {

        if (this.txtLogin.getText().equals("") || this.txtPassword.getPassword().toString().equals("")) {
            JOptionPane.showMessageDialog(null, "Campo vacío, verifique sus datos por favor", "error", JOptionPane.ERROR_MESSAGE);
        } else {
            String cadenaclave = "";
            String login = this.txtLogin.getText();
            char[] c = this.txtPassword.getPassword();
            for (int x = 0; x < c.length; x++) {
                char ch = c[x];
                String a = String.valueOf(ch);
                cadenaclave = cadenaclave + a;
            }

            // UsuarioJdbc userjdbc = new UsuarioJdbc();
            ManejadorUsuario user = new ManejadorUsuario();
            //Usuario u=userjdbc.iniciarSesionUsuario(login, cadenaclave);
            Usuario u = user.iniciarSesionUsuario(login, cadenaclave);
            userActual = u;
            if (u.getLogin_usuario() == null || u.getLogin_usuario().endsWith("_")) {
                JOptionPane.showMessageDialog(null, "Usuario No Existe, verifique sus datos", "error", JOptionPane.ERROR_MESSAGE);
            } else {
                final InfiniteProgressPanel glasspane = new InfiniteProgressPanel();
                this.setGlassPane(glasspane);
                glasspane.start();
                glasspane.setText("Iniciando sesion - ZonaSoft 1.0");
                this.setVisible(true);
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                        }
//                                JOptionPane.showMessageDialog(null, "Sesion Iniciada");
                        setVisible(false); 
     /* aqui termina la ejecucion de la ventana de inicio de sesion
        despues de validar como tal el inicio de sesion, incremento en 1 el numero de inicio de sesion*/
                        numeroInicio++;
    /* si el numero de eventos para iniciar sesion es igual a 1 muestrame la ventana principal
              esto para evitar que se ejecuten mas de una ventana principal */
                        boolean bandera = false;                                              
                        if (numeroInicio == 1) {
                            VentanaPrincipal.mostrar();
//                           try {
//                                mailMac.enviarAuditoriaSession();
//                                bandera=true;
//
//                            } catch (MessagingException ex) {
//                                System.out.println("ex = " + ex);
//                                bandera=false;
//                                Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
//                            }
//                           if (bandera == false){
//                           JOptionPane.showMessageDialog(null, "Verifique su conexion a internet","Error en Auditoria Online ",JOptionPane.PLAIN_MESSAGE);
//                            System.exit(0);
//                           }
//                           VentanaPrincipal.mostrar();
                          } // comprobacion de numero de logueos
                        
                    } // run
                });
                thread.start();
            }
            Date ahora = new Date();
            fechaInicioSesion = new Timestamp(ahora.getTime());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonInicioSesion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JPasswordField txtPassword;
    // End of variables declaration//GEN-END:variables
}
// asi estaba antes para acceder, en el primer  paquete la clase principal

/*

/* To change this template, choose Tools | Templates
 * and open the template in the editor.


package zonasoft;

import zonasoft.Vistas.VentanaPrincipal;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.watermark.SubstanceImageWatermark;

/**
 *
 * @author JORGE

public class Principal {

/**
 * @param args the command line arguments

public static void main(String[] args) {
// TODO code application logic here
VentanaPrincipal vp = new  VentanaPrincipal();


SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.BusinessBlackSteelSkin");

vp.setLocation(200, 200);
//vp.setSize(1500, 800);
vp.setLocationRelativeTo(null);
vp.setVisible(true);




}

}


 */
